import React, { useEffect, useState } from 'react'
import { Form, Button, Input, Modal, Row, Col, message, Upload, Select, DatePicker } from 'antd'
import { connect } from 'umi'

const FormItem = Form.Item
const { Option } = Select
import { getUploadUrl } from '@/utils/upload'
import { getUserInfo } from '../../service'
import { genderList, isAuditList } from '@/utils/constant'
import moment from 'moment'
import { UploadOutlined } from '@ant-design/icons'
import store from 'store2'

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
}

const AddForm = (props) => {
  const { onSubmit, onCancel, loading, visible, config, record, orgTree, currentUser } = props
  const [form] = Form.useForm()
  const [fileName, setFileName] = useState(null)
  const [fileList, setFileList] = useState([])
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState(null)

  useEffect(() => {
    if (visible) {
      const fieldsValue = store(`personnel-credential-` + currentUser.id)
      if (record) {
        form.setFieldsValue({
          ...record, birthday: moment(record.birthday).format('YYYY-MM-DD'),
          startTime: moment(record.startTime), endTime: moment(record.endTime), urls: record.fileUrl
        })
        let fileUrlList = record.fileUrl ? record.fileUrl.split(',') : []
        setFileList(fileUrlList.map((item, index) => {
          return {
            uid: index,
            url: item,
          }
        }))
      } else {
        if (fieldsValue) {
          form.setFieldsValue({
            ...fieldsValue, birthday: moment(fieldsValue.birthday).format('YYYY-MM-DD'),
            startTime: moment(fieldsValue.startTime), endTime: moment(fieldsValue.endTime)
          })
          setFileList(fieldsValue.fileList)
        }
        getUserInfo().then(res => {
          form.setFieldsValue({ ...res, birthday: moment(res.birthday).format('YYYY-MM-DD') })
        })
      }
    } else {
      form.resetFields()
      setFileList([])
    }
  }, [visible])

  const fileProps = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: (file)=>{
      return {name:file.name}
    },
    fileList: fileList,
    onChange (res) {
      const { status } = res.file
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`)
        } else {
          console.log(res.fileList)

          setFileList(res.fileList.map(
            (item) => {
              if (item.response) {
                return {
                  uid: item.uid,
                  name: item.name,
                  status: item.status,
                  url: item.response,
                }
              } else {
                return item
              }
            }
          ))
          message.success(`${res.file.name} 文件上传成功`)
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`)
      }
    },
    onRemove (info) {
      let urls = [...fileList]
      let index = urls.findIndex(item => item.uid === info.uid)
      if (index > -1) {
        urls.splice(index, 1)
      }
      setFileList(urls)
    }
  }

  const onFormCancel = () => {
    form.resetFields()
    setFileList([])
    onCancel()
  }

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    onSubmit({
      ...fieldsValue, fileUrl: fileList?.map(item => item.url).toString(),
      id: record && record.id, status: 0
    })
  }

  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }

  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    setPreviewVisible(true)
    setPreviewImage(file.url || file.preview)
  }

  const handleChange = () => {
    setPreviewVisible(false)
    setPreviewImage(null)
  }

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields()
    store(`personnel-credential-` + currentUser.id, { ...fieldsValue, fileList })
    message.success('信息暂存成功！')
  }

  const onReset = async () => {
    store.remove(`personnel-credential-` + currentUser.id)
    onFormCancel()
  }

  const footer = () => <>
    <div style={{ textAlign: 'center' }}><Button onClick={() => handleChange()}>关闭</Button></div>
  </>

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcard" label="身份证">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="gender" label="性别">
              <Select disabled={true}>
                {genderList.map((item, index) => {
                  return (
                    <Option value={`${item.value}`} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="birthday" label="出生年月">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialNo" label="证书编号" rules={[{ required: true, message: '证书编号不能为空' }]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="mangerNo" label="管理编号">
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="startTime" label="授予时间" rules={[{ required: true, message: '授予时间不能为空' }]}>
              <DatePicker placeholder="请选择授予时间" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="endTime" label="到期时间" rules={[{ required: true, message: '到期时间不能为空' }]}>
              <DatePicker placeholder="请选择到期时间" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialLevel" label="证书级别" rules={[{ required: true, message: '证书级别不能为空' }]}>
              <Select placeholder="请选择证书级别">
                {config.credentialLevel && config.credentialLevel.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobSeries" label="职称系列" rules={[{ required: true, message: '职称系列不能为空' }]}>
              <Select placeholder="请选择职称系列">
                {config.jobSeries && config.jobSeries.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialName" label="资格名称" rules={[{ required: true, message: '资格名称不能为空' }]}>
              <Input placeholder="请输入资格名称"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="profession" label="专业" rules={[{ required: true, message: '专业不能为空' }]}>
              <Select placeholder="请选择专业">
                {config.profession && config.profession.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="registerOrg" label="注册单位">
              <Input placeholder="请输入注册单位"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="approvalAuthority" label="批准机关" rules={[{ required: true, message: '批准机关不能为空' }]}>
              <Input placeholder="请输入批准机关"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="isAudit" label="是否年审">
              <Select placeholder="请选择年审状态">
                {isAuditList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="companyId" label='挂靠公司' rules={[{ required: true, message: '挂靠公司不能为空' }]}>
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {orgTree && orgTree.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urls" label="证件照片" rules={[{ required: true, message: '证件照片不能为空' }]}>
              <Upload {...fileProps} accept='.jpg,.png,.jpeg,.BMP' listType="picture-card" onPreview={handlePreview}>
                {fileList?.length >= 10 ? null : <><UploadOutlined/> 上传照片</>}
              </Upload>
            </FormItem>
            <Modal maskClosable={false} centered bodyStyle={{ padding: '20px' }} footer={footer()}
                   visible={previewVisible} closable={false}>
              <img alt="example" style={{ width: '100%' }} src={previewImage}/>
            </Modal>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        {
          !record && <Button onClick={() => onReset()}>重置</Button>
        }
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  }

  return (
    <Modal
      maskClosable={false}
      width='60%'
      destroyOnClose
      title='资质管理'
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AddForm)
